package cn.com.api.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.api.entity.ApiT_member;
import cn.com.api.entity.ApiU_circle;
import cn.com.api.entity.ApiU_circle_member;
import cn.com.api.entity.ApiU_message;
import cn.com.api.entity.ApiU_user_friend;
import cn.com.api.entity.ApiU_user_friend_group;
import cn.com.api.entity.ApiU_user_friend_group_detail;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.ApiU_circleService;
import cn.com.api.service.ApiU_circle_memberService;
import cn.com.api.service.ApiU_messageService;
import cn.com.api.service.ApiU_user_friendService;
import cn.com.api.service.ApiU_user_friend_groupService;
import cn.com.api.service.ApiU_user_friend_group_detailService;
import cn.com.api.service.CheckService;
import cn.com.util.*;

/**
 * 
 * 圈子成员
 */
@Controller
@RequestMapping(Utils.SYS_API + "circlemember/")
public class ApiU_circle_memberController {
	@Autowired
	private ApiU_circleService apiU_circleService;
	@Autowired
	private ApiU_circle_memberService apiU_circle_memberService;
	@Autowired
	private CheckService checkService;
	@Autowired
	private ApiT_memberService apiT_memberService;
	@Autowired
	private ApiU_messageService apiU_messageService;
	@Autowired
	private ApiU_user_friendService apiU_user_friendService;
	@Autowired
	private ApiU_user_friend_groupService apiU_user_friend_groupService;
	@Autowired
	private ApiU_user_friend_group_detailService apiU_user_friend_group_detailService;

	private static Logger logger = Logger.getLogger(ApiU_circle_memberController.class);

	/**
	 * 圈子成员列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "circlememberlist")
	public void circlememberlist(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String keyword, String circle_id, PageInfo pageInfo) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				paramMap.clear();
				paramMap.put("circle_id", circle_id);
				paramMap.put("status", "1");// 同意的成员
				if (keyword != null && !"".equals(keyword)) {
					paramMap.put("keyword", keyword);
				}
				List<ApiU_circle_member> memberlist = apiU_circle_memberService.getcirclemembersListPage(paramMap,
						pageInfo);
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("membertlist", memberlist);
				result.put("pageinfo", pageInfo);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功");
				map.put(Utils.DATAS, result);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 未加入圈子的好友成员列表（用户用户拉好友进圈子）
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "invatefriendslist")
	public void invatefriendslist(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String circle_id, PageInfo pageInfo) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user_id", user_id);
		params.put("status", 1);// 好友
		params.put("circle_id", circle_id);
		try {
			if (checkService.checkToken(user_id, token, map)) {
				List<ApiU_user_friend> ufriends = this.apiU_user_friendService.findU_user_friendByMap(params, pageInfo);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作完成！");
				map.put(Utils.DATAS, ufriends);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.objectToJsonStr(map));
	}

	/**
	 * 圈子成员禁言
	 * 
	 * @param silentids
	 *            禁言的u_circle_member表的id集合用：分隔
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "updatecirclemembersilent")
	public void updatecirclemembersilent(HttpServletRequest request, HttpServletResponse response, String user_id,
			String circle_id, String token, String silentids) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);

			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				map = apiU_circle_memberService.updatecirclemembersilent(circle_id, silentids);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 删除圈子成员
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "delcirclemember")
	public void delcirclemember(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String delids) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map = apiU_circle_memberService.delcirclemember(delids);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 圈主审核加入圈子的请求
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "auditjoinrequest")
	public void auditjoinrequest(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String circle_member_id, String status) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				map = apiU_circle_memberService.auditjoinrequest(circle_member_id, status);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 申请加入圈子（含邀请别人加入圈子）
	 * 
	 * @param user_id
	 *            操作人id，如果user_id和joinuserid不一致，便是邀请别人加入圈子
	 * @param joinuserids
	 *            申请加入圈子的用户id集合
	 * @param circle_id
	 *            要加入的圈子
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "joincircle")
	public void joincircle(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String joinuserids, String circle_id, String apply_msg) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				map = apiU_circle_memberService.joincircle(user_id, joinuserids, circle_id, apply_msg);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 获取申请加入圈子的信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getjoincircleinfo")
	public void getjoincircleinfo(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String circle_id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				PageInfo pageInfo = new PageInfo();
				paramMap.put("user_id", user_id);
				paramMap.put("circle_id", circle_id);
				List<ApiU_circle_member> list = apiU_circle_memberService.getcirclemembersListPage(paramMap, pageInfo);
				if (list != null && list.size() > 0) {
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "操作成功");
					map.put(Utils.DATAS, list.get(0));
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_NO_DATA);
					map.put(Utils.MESSAGE, "申请加入圈子");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * @Description: 圈主直接邀请别人加入圈子，不需要别人同意
	 * @param @param
	 *            request
	 * @param @param
	 *            response
	 * @param @param
	 *            user_id
	 * @param @param
	 *            token
	 * @param @param
	 *            circle_id
	 * @param @throws
	 *            Exception
	 * @return void
	 * @throws @author
	 *             yewl
	 * @date 2017年3月1日
	 */
	@RequestMapping(value = "addcirclemembers")
	@Transactional
	public void addcirclemembers(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String circle_id, String inviteuserids) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member qzmember = apiT_memberService.findT_memberById(Integer.valueOf(user_id));
		ApiU_circle apiU_circle = apiU_circleService.findU_circleById(Integer.valueOf(circle_id));
		// 消息信息存放list，用于最后批量提交
		List<ApiU_message> messagelist = new ArrayList<ApiU_message>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				String[] userids = inviteuserids.split(":");
				for (String joinid : userids) {
					ApiT_member join_member = apiT_memberService.findT_memberById(Integer.valueOf(joinid));
					map.put("user_id", joinid);
					map.put("circle_id", circle_id);
					ApiU_circle_member apiU_circle_member = apiU_circle_memberService.getcirclememberInfo(map);
					map.clear();
					if (apiU_circle_member != null) {// 该用户申请过或者原来是成员，之后推出或被踢出等
						apiU_circle_member.setAdd_time(DateUtil.nowTimeToString());
						apiU_circle_member.setIs_deal(0);
						apiU_circle_member.setIs_silent(0);
						apiU_circle_member.setUpdate_time("");
						apiU_circle_member.setStatus(1);
						apiU_circle_member.setNick_name(join_member.getC_nick());
						apiU_circle_memberService.updateU_circle_member(apiU_circle_member);
					} else {
						apiU_circle_member = new ApiU_circle_member();
						apiU_circle_member.setUser_id(joinid);
						apiU_circle_member.setAdd_time(DateUtil.nowTimeToString());
						apiU_circle_member.setIs_admin(0);
						apiU_circle_member.setIs_deal(0);
						apiU_circle_member.setIs_silent(0);
						apiU_circle_member.setNick_name(join_member.getC_nick());
						apiU_circle_member.setCircle_id(circle_id);
						apiU_circle_member.setStatus(1);
						apiU_circle_memberService.U_circle_memberInsertion(apiU_circle_member);
					}
					// 拉成员成功后，在系统消息中给被拉人提醒记录
					ApiU_message message = new ApiU_message();
					message.setAdd_time(DateUtil.nowTimeToString());
					message.setConn_id(apiU_circle_member.getId());
					message.setContent("你的好友" + qzmember.getC_nick() + "拉你加入" + apiU_circle.getCircle_name() + "圈子");
					message.setTitle("邀请加入圈子");
					message.setType(8);
					message.setUser_id(joinid);
					message.setIs_read(0);
					messagelist.add(message);
					// apiU_messageService.U_messageInsertion(message);

					// 添加消息分组
					ApiU_user_friend_group apiU_user_friend_group = this.apiU_user_friend_groupService
							.getUserFriendGroup(joinid, "我的消息");
					ApiU_user_friend_group_detail apiU_user_friend_group_detail = new ApiU_user_friend_group_detail();
					apiU_user_friend_group_detail.setFriend_group_id(apiU_user_friend_group.getId().toString());
					apiU_user_friend_group_detail.setAdd_time(Util.CurrentTime());
					apiU_user_friend_group_detail.setFriend_id(circle_id);
					apiU_user_friend_group_detail.setType(1);
					this.apiU_user_friend_group_detailService
							.U_user_friend_group_detailInsertion(apiU_user_friend_group_detail);
				}
				apiU_messageService.insertmessageList(messagelist);
			}
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "操作成功");
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 用户退出圈子
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "signoutcircle")
	public void signoutcircle(HttpServletRequest request, HttpServletResponse response, String user_id, String token,
			String circle_id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				map = apiU_circle_memberService.signoutcircle(user_id, circle_id);
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 成员修改圈子设置
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "updatecirclesetting")
	public void updatecirclesetting(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String member_circle_id, String is_top, String is_nointerrupt, String is_neglectnoread,
			String is_readdel) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				map.put("ids", member_circle_id.split(":"));
				if (is_top != null && !"".equals(is_top)) {
					map.put("is_top", is_top);
				}
				if (is_nointerrupt != null && !"".equals(is_nointerrupt)) {
					map.put("is_nointerrupt", is_nointerrupt);
				}
				if (is_neglectnoread != null && !"".equals(is_neglectnoread)) {
					map.put("is_neglectnoread", is_neglectnoread);
				}
				if (is_readdel != null && !"".equals(is_readdel)) {
					map.put("is_readdel", is_readdel);
				}
				apiU_circle_memberService.updatecirclememberinfo(map);
				map.clear();
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "操作成功");
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 转让圈子的圈主身份(创建人的身份也同时转给别人)
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "assignmentcircleadmin")
	public void assignmentcircleadmin(HttpServletRequest request, HttpServletResponse response, String user_id,
			String token, String assignor_id, String circle_id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("u_id", user_id);
			paramMap.put("token", token);
			if (checkService.checkToken(user_id, token, map) && checkService.checkParams(paramMap, map)) {
				map.clear();
				Integer result = apiU_circle_memberService.assignmentcircleadmin(user_id, assignor_id, circle_id);
				map.clear();
				if (result < 0) {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "不是圈主，无法转让");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "操作成功");
				}
			}
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "系统异常！");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

}
